// ignore_for_file: unused_import

/*
 * @Author: CodeHare
 * @Date: 2023-09-19 18:46:23
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-20 20:40:45
 * @Description: 自研-EMS远程控制
 */
import 'dart:async';
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/devices/device_list/device_list_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/self_develop_ems_romote_control/ems_romote_control/ems_romote_control_model.dart';
import 'package:yt_devops/pages/devices/device_tab/device_detail/ems/common/instruct_set_interface.dart';
import 'package:yt_devops/pages/tabs/device_tab/device_tab_controller.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/brn_row1_delegate.dart';
import 'package:yt_devops/utils/ems_enums.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'package:yt_devops/utils/socket/use_socket.dart';
import 'package:yt_devops/utils/socket/use_subscribe.dart';

class EmsRomoteControlController extends GetxController {
  DeviceServices deviceServices = Get.find<DeviceServices>();

  ConnectStatusType? connectStatus = ConnectStatusType.off;

  int? deviceId;
  int? productId;
  bool switchVal = false;

  /// 控制指令列表
  List<dynamic> systemStatusControlList = [
    SystemStatusControl(ResKey.deviceSystemStateControl.tr, "", null), //系统工作状态
    SystemStatusControl(ResKey.deviceSystemOperatingMode.tr, "", true), //系统操作模式
    SystemStatusControl(
        ResKey.deviceSystemOperatingMode.tr, "", true), // 系统工作模式控制
    SystemStatusControl(
        ResKey.deviceBatteryPackWorkingModeSwitch.tr, "", true), //电池组工作模式控制
    // SystemStatusControl("BMS主接触器控制", "", true),
    SystemStatusControl('siteMonitor.systemReset'.tr, "", true), //系统复位
  ];

  /// 底部弹选择框
  late List<dynamic> emsRomoteControlList = [];
  List<String> bottomPopList = [];
  int currentSelectIndex = -1;
  int selected = 0;
  String currentSelect = "";

  /// 指令集Socket值
  late Map instructSocketMap = {};

  /// 订阅在线状态数据流
  UseSubsribe emsOnlineStatusSubsribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsOnlineStatusSubscription;
  late Stream<Map<String, dynamic>> emsOnlineStatusBroadcastStream;

  /// 订阅指令值数据流
  UseSubsribe emsValSubscribe = UseSubsribe();
  StreamSubscription<Map<String, dynamic>>? emsValSubscription;
  late Stream<Map<String, dynamic>> emsValBroadcastStream;

  /// 请求参数策略
  SettingReqParams requestParams = SettingReqParams();

  @override
  void onInit() {
    super.onInit();

    _inheritValue();
    _renderList();
    _listenEmsOnlineStatusValue();
    _listenEmsControlValue();
  }

  /// 继承参数
  void _inheritValue() {
    deviceId = Get.arguments['deviceId'];
    productId = Get.arguments['productId'];
  }

  /// 渲染列表
  void _renderList() {
    emsRomoteControlList.addAll(systemStatusControlList);
  }

  /// 监听EMS设备在线状态
  void _listenEmsOnlineStatusValue() {
    emsOnlineStatusBroadcastStream = emsOnlineStatusSubsribe
        .start([deviceId!], true, type: MessageEventType.networkStatus)
        .stream
        .asBroadcastStream();

    emsOnlineStatusSubscription = emsOnlineStatusBroadcastStream.listen((data) {
      if (data['networkStatus'] != null) {
        connectStatus = $enumDecodeNullable(
          $ConnectStatusTypeEnumMap,
          data['networkStatus'],
        );
      }
    });
  }

  /// 监听EMS指令值
  void _listenEmsControlValue() {
    emsValBroadcastStream =
        emsValSubscribe.start([deviceId!], true).stream.asBroadcastStream();
    showLoading(toast: ResKey.loading.tr);

    emsValSubscription = emsValBroadcastStream.listen((data) {
      instructSocketMap = data;
      instructSocketMap.forEach((key, value) {
        String originData = value.toString();
        if (key == 'systemWorkingStatus') {
          // "0": "启动"
          // "1": "待机"
          // "2": "停止"
          // "3": "急停"
          if (originData == "0") {
            emsRomoteControlList[1].value = ResKey.thingsFiring.tr; //  启动
          } else if (originData == "1") {
            emsRomoteControlList[1].value = ResKey.thingsStandby.tr; // "待机";
          } else if (originData == "2") {
            emsRomoteControlList[1].value = ResKey.thingsCease.tr; //停止
          } else if (originData == "3") {
            emsRomoteControlList[1].value =
                ResKey.thingsEmergencyStop.tr; //  "急停";
          } else {
            emsRomoteControlList[1].value = "";
          }
        } else if (key == 'systemOperatingMode') {
          // "0": "削峰填谷"
          // "1": "备电"
          // "2": "手动控制"
          if (originData == "0") {
            emsRomoteControlList[2].value = ResKey.thingsPeakLoadShifting.tr;
            // "削峰填谷";
          } else if (originData == "1") {
            emsRomoteControlList[2].value = ResKey.thingsBackuppower.tr;
            // "备电";
          } else if (originData == "2") {
            emsRomoteControlList[2].value = ResKey.thingsManual.tr;
            //"手动控制";
          } else {
            emsRomoteControlList[2].value = "";
          }

          listenManualControl();
        } else if (key == 'batteryPackOperatingMode') {
          // "0": "正常"
          // "1": "核容"
          // "2": "均衡"
          // "3": "充电"
          // "4": "放电"
          if (originData == "0") {
            emsRomoteControlList[3].value = ResKey.normal.tr;
          } else if (originData == "1") {
            emsRomoteControlList[3].value = ResKey.thingsNuclearCapacity.tr;
            //"核容";
          } else if (originData == "2") {
            emsRomoteControlList[3].value = ResKey.thingsBalanced.tr; // "均衡";
          } else if (originData == "3") {
            emsRomoteControlList[3].value = ResKey.thingsCharge.tr; // "充电";
          } else if (originData == "4") {
            emsRomoteControlList[3].value = ResKey.thingsDischarge;
            // "放电";
          } else {
            emsRomoteControlList[3].value = "";
          }
        }

        // else if (key == 'bmsOpenAndClose') {
        //   // "0": "启动"
        //   // "1": "待机"
        //   // "2": "停止"
        //   if (originData == "0") {
        //     emsRomoteControlList[4].value = "断开";
        //   } else if (originData == "1") {
        //     emsRomoteControlList[4].value = "闭合";
        //   }
        // }
      });

      dismissLoading();
      update();
    });
  }

  /// 控制选择单元
  void controlUnit(context, item, index) {
    showBottomPop(context, item, index);

    update();
  }

  /// 监听手动控制系统工作模式
  void listenManualControl() {
    if (emsRomoteControlList[2].value == ResKey.thingsManual.tr) {
      useBmsBatteryPack();
    } else {
      forbidBmsBatteryPack();
    }
  }

  /// 禁用BMS主接触器与电池组工作模式控制
  void forbidBmsBatteryPack() {
    emsRomoteControlList[3].enabled = false;
    emsRomoteControlList[4].enabled = false;

    update();
  }

  /// 启用BMS主接触器与电池组工作模式控制
  void useBmsBatteryPack() {
    emsRomoteControlList[3].enabled = true;
    emsRomoteControlList[4].enabled = true;

    update();
  }

  /// 按动复位按钮
  void pushSwitch(value) {
    switchVal = value;

    update();
  }

  /// 弹出框文本状态
  dynamic judgeDialogText(item, cutrent, index) {
    if (item == null) {
      return ResKey
          .deviceWhetherExecuteSystemResetCommand.tr; // "是否执行复位指令，重启PCS？";
    } else {
      return "${item.label}为“${emsRomoteControlList[index].value}”，是否切换至“$cutrent”?";
    }
  }

  /// 收集控制指令请求参数
  Map<String, dynamic>? collectParams(item, index) {
    if (index == 1) {
      requestParams.input = {
        "systemWorkingStatus": currentSelectIndex.toString(),
      };
      return SystemWorkingStatus().trigger(deviceId.toString(), requestParams);
    } else if (index == 2) {
      requestParams.input = {
        "systemOperatingMode": currentSelectIndex.toString(),
      };
      return SystemOperatingMode().trigger(deviceId.toString(), requestParams);
    } else if (index == 3) {
      requestParams.input = {
        "batteryPackOperatingMode": currentSelectIndex.toString(),
      };
      return BatteryPackOperatingMode()
          .trigger(deviceId.toString(), requestParams);
    }
    // else if (index == 4) {
    //   requestParams.input = {
    //     "bmsOpenAndClose": currentSelectIndex.toString(),
    //   };
    //   return BMSMainContactorControl()
    //       .trigger(deviceId.toString(), requestParams);
    // }
    else {
      /// 复位参数
      return SystemReset().trigger(deviceId.toString(), requestParams);
    }
  }

  /// 下发指令接口
  void sendCommand(context, params, index) {
    Configs.httpClient.requestWithLoading(
      () async {
        var result = await deviceServices.deviceRemoteSetting(params);
        print("==== 结果 ==== $result");
        if (result == null) {
          FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);
        } else {
          afterCommandSuccess();
          if (index != emsRomoteControlList.length - 1) {
            emsRomoteControlList[index].value = currentSelect;
            update();
          }

          FuncUtils.requestTipsDislog(context, ResKey.executeSuccess.tr, true);
        }
        Future.delayed(
          const Duration(
            milliseconds: 1000,
          ),
          () => Get.back(),
        );
        update();
      },
      onError: (err) {
        FuncUtils.requestTipsDislog(context, ResKey.executeFailure.tr, false);
        Future.delayed(
          const Duration(
            milliseconds: 1000,
          ),
          () => Get.back(),
        );
        return true;
      },
    );
  }

  /// 指令下发成功后
  void afterCommandSuccess() {
    listenManualControl();
  }

  /// 弹窗
  void showDialog(BuildContext context, index, item, {isPress}) {
    BrnDialogManager.showConfirmDialog(
      context,
      title: "",
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      message: judgeDialogText(item, currentSelect, index),
      barrierDismissible: false,
      themeData: BrnDialogConfig(
        contentTextStyle: BrnTextStyle(
          color: Colour.mainTextColor,
          fontSize: 18.sp,
          fontWeight: FontWeight.w500,
        ),
        contentPaddingSm: EdgeInsets.symmetric(
          horizontal: 42.w,
        ),
        contentPaddingLg: EdgeInsets.symmetric(
          horizontal: 42.w,
        ),
      ),
      onConfirm: () async {
        if (isPress != null) {
          isPress = !isPress;
          pushSwitch(isPress);
        }

        var params = collectParams(item, index);
        sendCommand(context, params, index);
        Get.back();
      },
      onCancel: () {
        if (isPress != null) {
          isPress = !isPress;
          pushSwitch(isPress);
        }

        Get.back();
      },
    );
  }

  /// 赋值弹出框列表
  void assignBottomPopList(int index) {
    if (index == 1) {
      bottomPopList = [
        SystemWorkingStatusType.firing.label,
        SystemWorkingStatusType.standby.label,
        SystemWorkingStatusType.stop.label,
        SystemWorkingStatusType.emergencyStop.label,
      ];
    } else if (index == 2) {
      bottomPopList = [
        SystemOperatingModeType.peakLoadShifting.label,
        SystemOperatingModeType.backupPower.label,
        SystemOperatingModeType.manual.label,
      ];
    } else if (index == 3) {
      bottomPopList = [
        BatteryPackOperatingModeType.normal.label,
        BatteryPackOperatingModeType.nuclearCapacity.label,
        BatteryPackOperatingModeType.balanced.label,
        BatteryPackOperatingModeType.charging.label,
        BatteryPackOperatingModeType.discharging.label,
      ];
    }
    // else if (index == 4) {
    //   bottomPopList = [
    //     BMSMainContactorControlType.close.label,
    //     BMSMainContactorControlType.breakOff.label,
    //   ];
    // }
  }

  /// 列表展示为空时底部弹出框初始选中值
  void initEmptyBottomPopSelectedValue(int index) {
    var result = emsRomoteControlList[index].value.isEmpty!;
    if (result) {
      selected = 0;
    }

    update();
  }

  /// 弹出框选中值回显
  void echoBottomPopListSelected(int index) {
    if (index == 1) {
      initEmptyBottomPopSelectedValue(index);

      if (emsRomoteControlList[1].value == ResKey.thingsFiring.tr) {
        //启动
        selected = 0;
      } else if (emsRomoteControlList[1].value == ResKey.thingsStandby.tr) {
        // 待机
        selected = 1;
      } else if (emsRomoteControlList[1].value == ResKey.thingsCease.tr) {
        //待机
        selected = 2;
      } else if (emsRomoteControlList[1].value ==
          ResKey.thingsEmergencyStop.tr) {
        //急停
        selected = 3;
      }
    } else if (index == 2) {
      initEmptyBottomPopSelectedValue(index);
      if (emsRomoteControlList[2].value == ResKey.thingsPeakLoadShifting.tr) {
        // "削峰填谷"
        selected = 0;
      } else if (emsRomoteControlList[2].value == ResKey.thingsBackuppower.tr) {
        // 备电
        selected = 1;
      } else if (emsRomoteControlList[2].value == ResKey.thingsManual.tr) {
        // "手动控制"
        selected = 2;
      }
    } else if (index == 3) {
      initEmptyBottomPopSelectedValue(index);
      if (emsRomoteControlList[3].value == ResKey.normal.tr) {
        selected = 0;
      } else if (emsRomoteControlList[3].value ==
          ResKey.thingsNuclearCapacity.tr) {
        // "核容"
        selected = 1;
      } else if (emsRomoteControlList[3].value == ResKey.thingsBalanced.tr) {
        // "均衡"
        selected = 2;
      } else if (emsRomoteControlList[3].value == ResKey.thingsCharge.tr) {
        // "充电"
        selected = 3;
      } else if (emsRomoteControlList[3].value == ResKey.thingsDischarge.tr) {
        // "放电"
        selected = 4;
      }
    }
    // else {
    //   initEmptyBottomPopSelectedValue(index);
    //   if (emsRomoteControlList[4].value == "闭合") {
    //     selected = 0;
    //   } else if (emsRomoteControlList[4].value == "断开") {
    //     selected = 1;
    //   }
    // }
  }

  /// 弹出底部弹窗
  void showBottomPop(context, item, int index) {
    assignBottomPopList(index);
    echoBottomPopListSelected(index);

    BrnMultiDataPicker(
      context: Get.context!,
      title: item.label,
      confirmClick: (indexList) {
        currentSelectIndex = indexList[0];
        currentSelect = bottomPopList[indexList[0]];
        showDialog(context, index, item, isPress: null);
        update();
      },
      delegate: Brn1RowDelegate(
        bottomPopList,
        firstSelectedIndex: selected,
      ),
    ).show();
  }

  clickRadio(context, item, index) {
    if (connectStatus == ConnectStatusType.off || !item.enabled) return;

    controlUnit(context, item, index);
  }

  changeSwitch(context, value) {
    if (connectStatus == ConnectStatusType.off) {
      value = false;
      return;
    }

    showDialog(context, emsRomoteControlList.length - 1, null, isPress: value);
    pushSwitch(value);
  }

  @override
  void onClose() {
    emsOnlineStatusSubscription?.cancel();
    emsOnlineStatusSubsribe.closeListen();
    emsValSubscription?.cancel();
    emsValSubscribe.closeListen();

    super.onClose();
  }
}
